package com.katze.boot.plugins.shiro.authentication;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.katze.boot.common.utils.SpringContextUtils;
import com.katze.boot.plugins.redis.exception.TokenTimeoutException;
import com.katze.boot.plugins.shiro.ShiroProperties;
import com.katze.common.Code;
import com.katze.common.Message;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JWTFilter extends BasicHttpAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(JWTFilter.class);

    private static final String TOKEN = "Authentication";

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    private final String[] anonUrl ;

    public JWTFilter(ShiroProperties shiro){
        anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(shiro.getAnonUrl(), StringPool.COMMA);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        for (String url : anonUrl) {
            if (pathMatcher.match(url, httpServletRequest.getRequestURI())) return true;
        }
        if (isLoginAttempt(request, response)) {
            return executeLogin(request, response);
        }
        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        String token = req.getHeader(TOKEN);
        if (token != null) {
            return true;
        } else {
            rep.setStatus(401003);
            return false;
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        String token = httpRequest.getHeader(TOKEN);
        JWTToken jwtToken = new JWTToken(token, true);
        try {
            getSubject(request, response).login(jwtToken);
            return true;
        } catch (Exception e) {
            if (e instanceof TokenTimeoutException) {
                httpResponse.setStatus(401);
            } else if (e instanceof UnsupportedTokenException){
                httpResponse.setStatus(401001);
            } else if (e instanceof UnknownAccountException){
                httpResponse.setStatus(401002);
            } else if (e instanceof AuthenticationException){
                httpResponse.setStatus(401003);
            }
            log.error("访问失败:{}", e.getMessage());
            return false;
        }
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个 option请求，这里我们给 option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
        log.debug("Authentication required: sending 401 Authentication challenge response.");
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        String message;
        switch (httpResponse.getStatus()){
            case 401: message = "用户超时，请重新登录"; break;
            case 401001: message = "访问令牌绑定IP与当前IP不符"; break;
            case 401002: message = "用户名或密码错误"; break;
            case 401003: message = "访问令牌校验不通过"; break;
            default: message = "未知异常";
        }
        httpResponse.setStatus(HttpStatus.OK.value());
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("application/json; charset=utf-8");

        try (PrintWriter out = httpResponse.getWriter()) {
            String json = SpringContextUtils.getBean("jacksonObjectMapper", ObjectMapper.class).writeValueAsString(Message.exception(Code.C401, message));
            out.print(json);
        } catch (IOException e) {
            log.error("sendChallenge error：{}", message, e);
        }
        return false;
    }
}
